package com.glodon.paas.document.storage.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

import com.glodon.paas.document.storage.id.ObjectId;

public class VerifyInputStream extends InputStream {

    private InputStream in;
    private String objectId;
    private MessageDigest md;

    public VerifyInputStream(String objectId, InputStream in) {
        this.objectId = objectId;
        md = DigestState.createMessageDigest();
        this.in = new DigestInputStream(in, md);
    }

    @Override
    public int read() throws IOException {
        return in.read();
    }

    @Override
    public int hashCode() {
        return in.hashCode();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return in.read(b);
    }

    @Override
    public boolean equals(Object obj) {
        return in.equals(obj);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return in.read(b, off, len);
    }

    @Override
    public long skip(long n) throws IOException {
        return in.skip(n);
    }

    @Override
    public int available() throws IOException {
        return in.available();
    }

    @Override
    public String toString() {
        return in.toString();
    }

    @Override
    public void close() throws IOException {
        int available = in.available();
        in.close();
        if (available == 0) {
            ObjectId id = ObjectId.fromRaw(md.digest());
            if (!this.objectId.equals(id.name()))
                throw new IOException("verify resource sha failure, expect: " + this.objectId + ", actual: "
                        + id.name());
        }
    }

    @Override
    public void mark(int readlimit) {
        in.mark(readlimit);
    }

    @Override
    public void reset() throws IOException {
        in.reset();
    }

    @Override
    public boolean markSupported() {
        return in.markSupported();
    }
}
